package part21;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wcj
 * @Date 2021/6/9 15:48
 * @Version 1.0
 */
public class Part2115 {

 /**
  * Lock和Synchronized的区别：
  * ①前者API级别，显式加锁解锁；后者JVM级别，隐式加锁解锁
  * ②Lock支持非阻塞式获取锁
  * ③Lock支持响应中断
  * ④Lock支持超市等待机制
  *
  * @param args
  */
 public static void main(String[] args) {
  Part2115 p = new Part2115();
  p.testTryLock();
  p.testTryLockNanos();
  new Thread() {
   {
    setDaemon(true);
   }

   @Override
   public void run() {
    p.lock.lock();
    System.out.println("acquire");
   }
  }.start();
  Thread.yield();
  p.testTryLock();
  p.testTryLockNanos();
 }

 private ReentrantLock lock = new ReentrantLock();

 public void testTryLock() {
  boolean capture = lock.tryLock();
  try {
   System.out.println("capture:" + capture);
  } finally {
   if (capture) {
    lock.unlock();
   }
  }
 }

 public void testTryLockNanos() {
  boolean capture = false;
  try {
   capture = lock.tryLock(2, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  try {
   System.out.println("capture:" + capture);
  } finally {
   if (capture) {
    lock.unlock();
   }
  }
 }
}
